package com.api.syh56.shengyunhui.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import org.springframework.web.multipart.MultipartFile;


@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param file 要上传的文件
     * @return 文件上传成功后的访问路径
     */
    public String upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        if (file.isEmpty()) {
            log.error("文件为空");
            return null;
        }
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String formattedDate = now.format(formatter);

        // 使用格式化的日期构造新文件名称
        String objectName = formattedDate + "/" + UUID.randomUUID().toString() + extension;
//        System.out.println(objectName);
            byte[] bytes;
            // 将文件转换为字节数组
            try {
                bytes = file.getBytes();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            try {
                // 创建PutObject请求。
                ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
            } catch (OSSException oe) {
                log.error("文件上传失败：");
                log.error("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                log.error("Error Message:" + oe.getErrorMessage());
                log.error("Error Code:" + oe.getErrorCode());
                log.error("Request ID:" + oe.getRequestId());
                log.error("Host ID:" + oe.getHostId());
                return null;
            } catch (ClientException ce) {
                log.error("文件上传失败：");
                log.error("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                log.error("Error Message:" + ce.getMessage());
                return null;
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
            return generateUrl(objectName);
    }

    /**
     * 生成文件访问的URL
     *
     * @param objectName 对象名称
     * @return 文件访问的URL
     */
    private String generateUrl(String objectName) {
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder.append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);
        return stringBuilder.toString();
    }
}
